package com.wgchao.identityrightsmanagement.application.controller;

import com.wgchao.identityrightsmanagement.infrastructure.exception.DefinedException;
import com.wgchao.identityrightsmanagement.infrastructure.utils.ResponseData;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName: GlobalExceptionHandler
 * @author: wgchao
 * @createTime: 2020/6/28 11:32 AM
 * @Description: TODO
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(DefinedException.class)
    public ResponseData exceptionHandler(HttpServletRequest request, DefinedException exception) throws Exception {
        return handleErrorInfo(request, exception.getMessage(), exception);
    }

    @ExceptionHandler(Exception.class)
    public ResponseData exceptionHandler(HttpServletRequest request, Exception exception) throws Exception {
        return handleErrorInfo(request, exception.getMessage(), exception);
    }

    private ResponseData<String> handleErrorInfo(HttpServletRequest request, String message, Exception exception) {
        exception.printStackTrace();
        if(exception instanceof DefinedException){
            DefinedException definedException = (DefinedException) exception;
            return ResponseData.error(definedException.getCode(), definedException.getMessage());
        }else{
            return ResponseData.error(message);
        }
    }
}

